<?php
/**
 * Created by PhpStorm.
 * 楼小二端接口
 * User: caicm
 * Date: 2017/2/18
 * Time: 9:13
 */

namespace SDXApi\Controller;
use SDXApi\Model\LouxiaoerGroupUserModel;
use SDXApi\Model\LouxiaoerGroupModel;
use SDXApi\Model\LouxiaoerOrderModel;
use SDXApi\Model\LouxiaoerUserModel;
use Common\Api\Ali_ossApi;
use Think\Controller;
use Think\Model;


class LouxiaoerController extends AppController
{

    public $wprow;
    protected $louxiaoer_user;
    protected $louxiaoer_order;
    protected $louxiaoer_group;
    protected $louxiaoer_group_user;


    public function _initialize($apptoken = '', $apptime = '', $check_uid = false, $session_id = '', $check_sign = true, $set_action = true)
    {
        parent::_initialize($apptoken, $apptime, $check_uid, $session_id, false);

        $warehouse_personnel = M('warehouse_personnel');
        $user_id = I('request.user_id', 'intval');
        $this->wprow = $warehouse_personnel->field('position,wid,uid,longitude,latitude,status')->where(array('uid' => $user_id, 'position' => 5, 'status' => 1))->find();

        if (!$this->wprow && $_SERVER['SERVER_NAME']=='api.shidexian.com') {
            returnApiError("无此操作权限");
        }

        $this->louxiaoer_user = new LouxiaoerUserModel();
        $this->louxiaoer_order = new LouxiaoerOrderModel();
        $this->louxiaoer_group = new LouxiaoerGroupModel();
        $this->louxiaoer_group_user = new LouxiaoerGroupUserModel();

    }

    /*
     * 获取统计数据
     * Created By caicm
     */
    public function get_count(){

        $user_id = I('user_id',0,'int');             //楼小二id

        if(!$user_id) returnApiError("user_id不能为空");

        $data['count_member'] = $this->louxiaoer_user->findCountUser($user_id);
        $data['count_today_order'] = $this->louxiaoer_order->count_today_order($user_id);

        $data['count_louxiaoer'] = M('louxiaoer_order')->where('louxiaoer_id=0')->count();

        $data['count_group'] = $this->louxiaoer_group->findGroupCount($user_id);

        $data['count_check_order'] = $this->louxiaoer_order->count_check_order($user_id);

        returnApiSuccess($data);

    }

    /*
     * 新建群组
     * Created By caicm
     */
    public function group_create(){

        $user_id = I('user_id',0,'int');    //楼小二id
        $name = I('name');                   //群组名称

        if(!$user_id) returnApiError("user_id不能为空");
        if(!$name) returnApiError("name不能为空");

        if(!$this->louxiaoer_group->findGroup($user_id, $name)){

            if($this->louxiaoer_group->addGroup($user_id, $name)){
                returnApiSuccess(null, '操作成功！');
            }else{
                returnApiError("操作失败！");
            }

        }else{
            returnApiError("该群组名称已存在！");
        }

    }

    /*
     * 群组列表
     * Created By caicm
     */
    public function group_list(){

        $user_id = I('user_id',0,'int');        //楼小二id
        $page = I('page',1,'int');              //分页数

        if(!$user_id) returnApiError("user_id不能为空");

        $count = $this->louxiaoer_group->findGroupCount($user_id);

        $pagearr=show_page($count, $page);

        if($page>=$pagearr['pagecount']){
            $data['is_last'] = 1;
        }else{
            $data['is_last'] = 0;
        }

        $limit = $pagearr['firstpage'].','.$pagearr['pagesize'];

        $list = $this->louxiaoer_group->findGroupList($user_id, $limit);
        foreach($list as $key=>$val){
            $list[$key]['count_member'] = $this->louxiaoer_group_user->findCountUser($val['id'], $user_id);
        }

        $data['list'] = $list;
        $data['count'] = $count;

        if(count($data['list'])>0){
            returnApiSuccess($data,'已经返回数据');
        }else{
            returnApiSuccess($data,'无数据');
        }

    }

    /*
     * 添加会员到群组
     * Created By caicm
     */
    public function group_add_member(){

        $user_id = I('user_id',0,'int');            //楼小二id
        $member_id = I('member_id',0,'int');        //会员id
        $group_id = I('group_id',0,'int');          //群组id

        if(!$user_id) returnApiError("user_id不能为空");
        if(!$member_id) returnApiError("member_id不能为空");
        if(!$group_id) returnApiError("group_id不能为空");

        //分组是否存在
        $group_count = $this->louxiaoer_group->findGroupCount($user_id,  $group_id);
        if(!$group_count) returnApiError("分组未存在！");

        //用户是否存在
        $louxiaoer_user = $this->louxiaoer_user->findLouxiaoerUserById( $member_id);
        if(!$louxiaoer_user) returnApiError("会员不存在！");

        //是否已绑定分组
        $group_user = $this->louxiaoer_group_user->finGroupUser($member_id, $group_id);
        if($group_user) returnApiError("该用户已绑定到该分组！");

        $val = $this->louxiaoer_group_user->bindingUserToGroup($member_id, $group_id);

        if($val){
            returnApiSuccess(null, '操作成功！');
        }else{
            returnApiError("操作失败！");
        }

    }

    /*
     * 删除群组的会员
     * reated By caicm
     */
    public function group_del_member(){
        $user_id = I('user_id',0,'int');            //楼小二id
        $member_id = I('member_id',0,'int');        //会员id
        $group_id = I('group_id',0,'int');          //群组id

        if(!$user_id) returnApiError("user_id不能为空");
        if(!$member_id) returnApiError("member_id不能为空");
        if(!$group_id) returnApiError("group_id不能为空");

        $val = $this->louxiaoer_group_user->delUserToGroup($member_id, $group_id);

        if($val){
            returnApiSuccess(null, '操作成功！');
        }else{
            returnApiError("操作失败！");
        }
    }

    /*
     * 删除群组
     */
    public function group_del(){

        $user_id = I('user_id',0,'int');        //楼小二id
        $group_id = I('group_id',0,'int');      //群组id

        if(!$user_id) returnApiError("user_id不能为空");
        if(!$group_id) returnApiError("group_id不能为空");

        //分组是否存在
        $group_count = $this->louxiaoer_group->findGroupCount($user_id,  $group_id);
        if(!$group_count) returnApiError("分组未存在！");

        //删除群组
        $this->louxiaoer_group->delGroup($user_id,  $group_id);


        //清除用户绑定群组
        $this->louxiaoer_group_user->delUserToGroup(0, $group_id);

        returnApiSuccess(null, '操作成功！');


    }

    /*
     * 会员列表
     * Created By caicm
     */
    public function member_list(){
        $user_id = I('user_id',0,'int');         //楼小二id
        $group_id = I('group_id',0,'int');      //群组id（选）
        $page = I('page',1,'int');              //分页
        $type = I('type',0,'int');              //类型（选）
        $keyword = I('keyword');                //关键词（选）
        $check_group_id = I('check_group_id',0,'int'); //有值返回会员是否在改组字段

        if(!$user_id) returnApiError("user_id不能为空");


        $totle = $this->louxiaoer_user->findMemberCount($user_id, $group_id, $keyword, $type);


        $pagearr=show_page($totle, $page);

        if($page>=$pagearr['pagecount']){
            $data['is_last'] = 1;
        }else{
            $data['is_last'] = 0;
        }

        $limit = $pagearr['firstpage'].','.$pagearr['pagesize'];

        $list = $this->louxiaoer_user->findMemberList($user_id, $group_id, $limit, $keyword, $type);

        //查询用户订单数量
        foreach($list as $key=>$val){
            $list[$key]['count_order'] = $this->louxiaoer_order->findCountOrderByLouxiaoerId($user_id, $val['user_id']);
            if($check_group_id){
                $list[$key]['exist'] = $val['group_id']==$check_group_id ? 1 : 0;
            }
            $list[$key]['address'] ="[{$val['region']}]" . $val['address'] . '-' . $val['sign_building'] . '-' . $val['address_name'];
            $list[$key]['group_info']  = $this->get_group($val['user_id']);
            unset($list[$key]['sign_building']);
            unset($list[$key]['address_name']);
            unset($list[$key]['region']);
        }


        $data['list'] = $list;
        $data['count'] = $totle;

        if(count($data['list'])>0){
            returnApiSuccess($data,'已经返回数据');
        }else{
            returnApiSuccess($data,'无数据');
        }

    }

    /*
     * 会员备注
     * Created By caicm
     */
    public function member_remark(){

        $user_id = I('user_id',0,'int');        //楼小二id
        $member_id = I('member_id',0,'int');    //会员id
        $remark = I('remark');                  //备注内容

        if(!$user_id) returnApiError("user_id不能为空");
        if(!$member_id) returnApiError("group_id不能为空");
        if(!$remark) returnApiError("remark不能为空");

        $val = $this->louxiaoer_user->addRemark($user_id, $member_id, $remark);

        if($val){
            returnApiSuccess(null, '操作成功！');
        }else{
            returnApiError("操作失败！");
        }

    }

    /*
     * 获取会员当天订单url
     * Created By caicm
     */
    public function today_order_url(){

        $user_id = I('user_id',0,'int');        //楼小二id

        if(!$user_id) returnApiError("user_id不能为空");

        $data['url'] = C("SDX_SEND_DOMIANURL")."admin/louxiaoer_service.php?act=main&app_action=1&louxiaoer_id=$user_id";
        $data['url_louxiaoer'] = C("SDX_SEND_DOMIANURL")."index.php?m=admin&c=louxiaoer_service&a=binding_landramk&louxiaoer_id=$user_id";

        returnApiSuccess($data,"已返回数据");

    }

    /*
     * 查看会员备注（url）
     * Created By caicm
     */
    public function get_remark_url(){

        $user_id = I('user_id',0,'int');        //楼小二id
        $member_id = I('member_id',0,'int');        //用户id

        if(!$user_id || !$member_id) returnApiError("user_id不能为空");

        $data['url'] = C("SDX_SEND_DOMIANURL")."index.php?m=admin&c=user_tag&a=order_user_tag&order_id=&user_id=$user_id&member_id=$member_id";

        returnApiSuccess($data,"已返回数据");

    }

    /*
     * 订单列表
     * Created By caicm
     */
    public function order_list(){

        $user_id = I('user_id',0,'int');         //楼小二id
        $member_id = I('member_id',0,'int');      //用户id
        $page = I('page',1,'int');              //分页

        if(!$user_id || !$member_id) returnApiError("参数有误");

        //获取用户id
        $uid = M('louxiaoer_user')->where("id={$member_id}")->getField('user_id');

        $totle = $this->louxiaoer_order->findOrderCount($user_id, $uid);

        $pagearr=show_page($totle, $page);

        if($page>=$pagearr['pagecount']){
            $data['is_last'] = 1;
        }else{
            $data['is_last'] = 0;
        }

        $limit = $pagearr['firstpage'].','.$pagearr['pagesize'];



        $list = $this->louxiaoer_order->findOrderList($user_id, $uid, $limit);
        foreach($list as $key=>$val){

            $list[$key]['time'] = local_date('Y-m-d H:i:s',$val['time']) . ($val['louxiaoer_user_id']==$member_id?'':" ({$val['name']})") ;
            unset($list[$key]['louxiaoer_user_id']);
            unset($list[$key]['name']);
        }

        $data['list'] = $list;

        if(count($data['list'])>0){
            returnApiSuccess($data,'已经返回数据');
        }else{
            returnApiSuccess($data,'无数据');
        }

    }

    /*
     * 订单备注
     * Created By caicm
     */
    public function order_remark(){
        $user_id = I('user_id',0,'int');         //楼小二id
        $order_id = I('order_id',0,'int');      //订单id
        $remark = I('remark');                  //备注内容

        if(!$user_id || !$order_id || !$remark) returnApiError("参数有误");

        $data = $this->louxiaoer_order->findOrderInfo($order_id, $user_id);

        if(!$data) returnApiError("订单不存在");

        $action_data = array(
            'order_id' => $order_id,
            'action_user' => "【楼小二】{$data['louxiaoer_name']}",
            'order_status' => $data['order_status'],
            'shipping_status' => $data['shipping_status'],
            'pay_status' => $data['pay_status'],
            'action_place' => 0,
            'action_note' => $remark,
            'log_time' => gmtime()
        );
        $action_id = M('order_action')->data($action_data)->add();

        $log_data = array(
            'user_id' => $data['user_id'],
            'order_id' => $order_id,
            'louxiaoer_id' => $user_id,
            'landmark_id' => $data['landmark_id'],
            'action_id' => $action_id,
            'add_time' => gmtime()
        );

        M('louxiaoer_order_log')->data($log_data)->add();

        returnApiSuccess(null, '操作成功！');

    }

    /*
     * 获取微信信息
     * Created By caicm
     */
    public function get_wechat_info(){

        $user_id = I('user_id',0,'int');        //楼小二id

        if(!$user_id) returnApiError("user_id不能为空");

        $user_info = M('warehouse_personnel')->field('wechat_name,wechat_barcode_img')->where("uid=$user_id")->find();
        $user_info['wechat_barcode_img'] = C('CDN_IMG_HOST').'/'.$user_info['wechat_barcode_img'];
        returnApiSuccess($user_info, '操作成功！');

    }

    /*
     * 更新微信信息
     * Created By caicm
     */
    public function set_wechat_info(){
        $user_id = I('user_id',0,'int');         //楼小二id
        $wechat_name = I('wechat_name');         //微信账号

        if(!$user_id || !$wechat_name ) returnApiError("参数有误");

        if($_FILES['wechat_barcode_img']['name']){
            $path = "uploads/louxiaoer_wechat/".date('YmdHis').mt_rand(1000,9999).".".end(explode('.', $_FILES['wechat_barcode_img']['name']));
            Ali_ossApi::upload($path, $_FILES['wechat_barcode_img']['tmp_name']);
            $data['wechat_barcode_img'] = $path;
        }

        $data['wechat_name'] = $wechat_name;

        $val = M('warehouse_personnel')->where("uid=$user_id")->data($data)->save();
        if($val){
            returnApiSuccess(null, '操作成功！');
        }else{
            returnApiError("操作失败！");
        }
    }

    /*
     * 会员可添加的群组列表
     * Created By caicm
     */
    public function get_group_list_with_member(){

        $user_id = I('user_id',0,'int');         //楼小二id
        $member_id = I('member_id',0,'int');         //会员id

        if(!$user_id || !$member_id ) returnApiError("参数有误");

        $list = $this->louxiaoer_group->get_group_list_with_member($user_id, $member_id);

        if($list){
            $data['list'] = $list;
            returnApiSuccess($data);
        }else{
            returnApiError("暂无可添加分组");
        }

    }

    /*
     * 获取订单列表
     * Created By caicm
     */
    public function get_order_list_with_date(){
        $user_id = I('user_id',0,'int');         //楼小二id
        $page = I('page',1,'int');              //分页
        $year = I('year');      //年
        $month = I('month');      //月
        $day = I('day');      //日

        $keyword = I('keyword');        //搜索(姓名、地址、订单号)
        $buy_type = I('buy_type',0,'int');         //0全部，1首单，2复单
        $use_date = I('use_date',0,'int');         //0全部，1按指定日期



        if(!$user_id ) returnApiError("参数有误");

        $time_start = 0;
        $time_end = 0;

        if($use_date == 1){
            if(!$year || !$month || !$day ) returnApiError("参数有误");
            $time_start = strtotime($year.'-'.$month.'-'.$day)-28800; //开始时间
            $time_end = $time_start + 86400 ;   //结束时间(1天)
        }

        $totle = $this->louxiaoer_order->get_order_list_with_date_count($user_id, $keyword, $buy_type, $time_start, $time_end);

        $pagearr=show_page($totle, $page);

        if($page>=$pagearr['pagecount']){
            $data['is_last'] = 1;
        }else{
            $data['is_last'] = 0;
        }

        $limit = $pagearr['firstpage'].','.$pagearr['pagesize'];


        $list = $this->louxiaoer_order->get_order_list_with_date($user_id, $keyword, $buy_type, $time_start, $time_end, $limit);

        foreach ($list as $key=>$val){

            $list[$key]['buy_info'] = $val[is_first]?'复购':'首购';
            $list[$key]['is_first'] = $val[is_first]?$val[is_first]:0;
            $list[$key]['member_id'] = $val[member_id]?$val[member_id]:0;
            $list[$key]['group_info']  = $this->get_group($val['member_id']);
            $list[$key]['time'] = local_date('Y-m-d H:i:s',$val['time']);
        }

        $data['count_order'] = $totle;
        $data['list'] = $list;

        if($list){
            returnApiSuccess($data);
        }else{
            returnApiError("无数据！");
        }

    }


    protected function get_group($menber_id){
        $info = array();
        $list = $this->louxiaoer_group_user->get_group_list($menber_id);
        foreach ($list as $value){
            $info[] = '【'.$value['group_name'].'】';
        }

        return $info ? implode(' , ', $info) : '暂无分组';
    }

}